package com.jn.erp.web.api.interaction.service.impl;


import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jn.erp.web.api.common.mapper.TLabelMapper;
import com.jn.erp.web.api.course.entity.TCourseOrder;
import com.jn.erp.web.api.course.entity.dto.TCourseOrderDto;
import com.jn.erp.web.api.course.mapper.TCourseOrderMapper;
import com.jn.erp.web.api.course.service.TCourseOrderService;
import com.jn.erp.web.api.interaction.entity.*;
import com.jn.erp.web.api.interaction.entity.vo.TEvaluateVo;
import com.jn.erp.web.api.interaction.mapper.*;
import com.jn.erp.web.api.interaction.service.TEvaluateService;
import com.obs.services.ObsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wyp
 * @since 2024-09-20
 */
@Service
public class TEvaluateServiceImpl extends ServiceImpl<TEvaluateMapper, TEvaluate> implements TEvaluateService {
    @Autowired
    private TEvaluateScoreMapper tEvaluateScoreMapper;

    @Autowired
    private TEvaluateTemplateMapper tEvaluateTemplateMapper;

    @Autowired
    private TLabelMapper tLabelMapper;

    @Autowired
    private TEvaluateMapper tEvaluateMapper;

    @Autowired
    private TCourseOrderMapper tCourseOrderMapper;

    @Autowired
    private TIntegralConfigMapper tIntegralConfigMapper;

    @Autowired
    private TIntegralMapper tIntegralMapper;



    @Autowired
    private TCourseOrderService tCourseOrderService;

    @Override
    public Map count(TEvaluateVo tEvaluateVo) {
        Map map = baseMapper.count(tEvaluateVo);
        return map;
    }

    @Override
    public TEvaluate evaluateGetById(TEvaluateVo tEvaluateVo) {
        TEvaluate tEvaluate = baseMapper.selectById(tEvaluateVo.getId());
        // 评价id
        List<TEvaluateScore> tEvaluateScores = tEvaluateScoreMapper.selSorce(tEvaluateVo);
//        List<TEvaluateScore> tEvaluateScores = tEvaluateScoreMapper.selectList(new QueryWrapper<TEvaluateScore>().eq("is_delete", "0").eq("e_id", tEvaluateVo.getId()));

        tEvaluate.settEvaluateScores(tEvaluateScores);
//        Long templateId = Objects.isNull(tEvaluateVo.getTemplateId()) ? tEvaluate.getTemplateId() : tEvaluateVo.getTemplateId();
//        TEvaluateTemplate tEvaluateTemplate = tEvaluateTemplateMapper.selectById(templateId);
//        List<TLabel> tLabelList = tLabelMapper.selectList(new QueryWrapper<TLabel>().in("id", tEvaluateTemplate.getInfo()));
//        tEvaluate.setTLabelList(tLabelList);
        return tEvaluate;

    }


    @Override
    @Transactional
    public String updateEvaluate(TEvaluateVo tEvaluateVo) {
        Boolean tIntegralFlag = false;
        // 修改评价信息
        // 修改学员id  统一
        List<TEvaluate> ids = tEvaluateVo.getIds();
        for (TEvaluate evaluate : ids) {
            TEvaluate tEvaluate = baseMapper.selectById(evaluate.getId());
            // 判断是否添加积分
            if (1 == tEvaluate.getState() && 0 == tEvaluateVo.getState()) {
                tIntegralFlag = true;
            }
            tEvaluate.settId(evaluate.getTid());
            tEvaluate.setId(evaluate.getId());
            // 设置成已点评
            tEvaluate.setState(0);
            tEvaluate.setTemplateId(tEvaluateVo.getTemplateId());
            tEvaluate.setEvaluator(Long.valueOf(tEvaluateVo.getUpdateUser()));
            tEvaluate.setDescription(tEvaluateVo.getDescription());
            tEvaluate.setUpdateDate(LocalDateTime.now());
            tEvaluate.setUpdateUser(tEvaluateVo.getCreateUser());
            // 上传 图片/视频/音频
            List<String> list = tEvaluateVo.getUrl();
            ArrayList<String> url = new ArrayList<>();
            for (String s : list) {
                // 上传图片
                url.add(s);
                String pic = url.stream().map(String::valueOf).collect(Collectors.joining(","));
                tEvaluate.setLink(pic);
            }
            int i = baseMapper.updateById(tEvaluate);

        // 添加评价分数
        TEvaluateScore tEvaluateScore = new TEvaluateScore();
        tEvaluateScore.setIsDelete("1");
        int eId = tEvaluateScoreMapper.update(tEvaluateScore, new QueryWrapper<TEvaluateScore>().eq("e_id", tEvaluateVo.getId()));

        for (TEvaluateScore evaluateScore : tEvaluateVo.gettEvaluateScores()) {
            evaluateScore.setCreateUser(tEvaluateVo.getUpdateUser());
            evaluateScore.setCreateDate(LocalDateTime.now());
            evaluateScore.setEId(evaluate.getId());
            evaluateScore.setlId(evaluateScore.getlId());
            evaluateScore.setId(null);
            tEvaluateScoreMapper.insert(evaluateScore);
        }
//        if (tIntegralFlag) {
//            //添加积分
//            TIntegralConfig t = tIntegralConfigMapper.selectOne(new QueryWrapper<TIntegralConfig>().eq("org_id", tEvaluateVo.getOrgId()).eq("is_delete", "0"));
//            if (!Objects.isNull(t)) {
//                TIntegral tIntegral = new TIntegral(tEvaluateVo.getOrgId(),evaluate.gettId(), t.getId(), 3, t.getAttr3(), t.getName(), "评价", LocalDateTime.now(), String.valueOf(tEvaluateVo.getUpdateUser()), null, null, "0");
//                tIntegralMapper.insert(tIntegral);
//            }
//        }

    }
        return "S200";
    }

    @Override
    public List<TCourseOrderDto> evaluateStudentList(TEvaluateVo tEvaluateVo) {
        return tCourseOrderMapper.evaluateStudentList(tEvaluateVo);

    }

    @Override
    public List<TCourseOrderDto> evaluationRecordsList(TEvaluateVo tEvaluateVo) {
        return tCourseOrderMapper.evaluationRecordsList(tEvaluateVo);
    }

    @Override
    public ArrayList<String> upload(List<MultipartFile> file) {
        // 填写一些必要的信息
        String endPoint = "obs.cn-north-9.myhuaweicloud.com";
        String ak = "UA0FTXCDHHVIOPSUEN3Y";
        String sk = "2bGZCIA9z4f5aKuJ8uenT09Mpf5xSinINOTIDdew";
        String bucketName = "zsrdkj-bucket";
        // 创建ObsClient实例
        ObsClient obsClient = new ObsClient(ak, sk, endPoint);
        ArrayList<String> pic = new ArrayList<>();
        try {
            String fileName = "";
            // 获取文件流
            for (MultipartFile multipartFile : file) {
                InputStream inputStream = multipartFile.getInputStream();
                String originalFilename = multipartFile.getOriginalFilename();
                // 如果传的是图片
                if (originalFilename.endsWith(".jpg") || originalFilename.endsWith(".jpeg")
                        || originalFilename.endsWith(".bmp")
                        || originalFilename.endsWith(".gif")
                        || originalFilename.endsWith(".png")) {

                    // 根据年月日创建一个文件夹，方便管理图片信息
                    // 图片路径
                    fileName = "zsrd-tp/" + new DateTime().toString("yyyy/MM/dd") + UUID.randomUUID().toString().replace("-", "") + originalFilename;
                }
                // 视频的路径
                else if (originalFilename.endsWith(".mp4") || originalFilename.endsWith(".avi")
                        || originalFilename.endsWith(".mov")
                ) {
                    // 根据年月日创建一个文件夹，方便管理图片信息
                    // 图片路径
                    fileName = "zsrd-sp/" + new DateTime().toString("yyyy/MM/dd") + UUID.randomUUID().toString().replace("-", "") + originalFilename;
                }
                // 音频的路径
                else if (originalFilename.endsWith(".mp3") || originalFilename.endsWith(".mp2")
                        || originalFilename.endsWith(".wav")
                ) {
                    // 根据年月日创建一个文件夹，方便管理图片信息
                    // 图片路径
                    fileName = "zsrd-yp/" + new DateTime().toString("yyyy/MM/dd") + UUID.randomUUID().toString().replace("-", "") + originalFilename;
                }
                // 使用文件流的方式上传 -- 创建PutObject请求
                obsClient.putObject(bucketName, fileName, inputStream);

                // 返回图片地址进行保存
                // https://xianzeng.obs.cn-north-4.myhuaweicloud.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20220908100029.jpg
                System.out.println("https://" + bucketName + "." + endPoint + "/" + fileName);
                String s = "https://" + bucketName + "." + endPoint + "/" + fileName;
                pic.add(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (obsClient != null) {
                try {
                    obsClient.close(); // 关闭资源
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return pic;
    }


    @Override
    public void delete(List<String> url) {
        // 填写一些必要的信息
        String endPoint = "obs.cn-north-9.myhuaweicloud.com";
        String ak = "UA0FTXCDHHVIOPSUEN3Y";
        String sk = "2bGZCIA9z4f5aKuJ8uenT09Mpf5xSinINOTIDdew";
        String bucketName = "zsrdkj-bucket";
        // 创建ObsClient实例
        ObsClient obsClient = new ObsClient(ak, sk, endPoint);
        try {
            for (String s : url) {
                obsClient.deleteObject(bucketName, s);
            }
        } catch (Exception e) {
            // 其他异常信息打印
            e.printStackTrace();

        }
    }

    @Override
    public List<TCourseOrderDto> evaluateTeacherList(TEvaluateVo evaluateTeacherList) {
        return tCourseOrderMapper.evaluateTeacherList(evaluateTeacherList);
    }

    @Override
    public List<TEvaluate> evaluateUnifyList(TEvaluateVo tEvaluateVo) {
//        List<TEvaluate> list = this.list(new QueryWrapper<TEvaluate>().eq("order_no", tEvaluateVo.getOrderNo()).eq("is_delete", "0").eq("state", tEvaluateVo.getState()).eq("type",1));
        List<TEvaluate> list = tEvaluateMapper.selList(tEvaluateVo);
        if(list.size()>0){
           Long studentId=list.get(0).gettId();
            TCourseOrder courseOrder =tCourseOrderService.getOne(new QueryWrapper<TCourseOrder>().eq("order_no", tEvaluateVo.getOrderNo()).eq("is_delete", "0").eq("org_id", tEvaluateVo.getOrgId()).eq("student_id", studentId));
            for (TEvaluate tEvaluate : list) {
                if (courseOrder.getTeacher() == Long.valueOf(tEvaluateVo.getCreateUser())) {
                    tEvaluate.setCode("0");
                } else {
                    tEvaluate.setCode("1");
                }
            }
        }
        return list;
    }
}




